/*
 * Licensed to the 南京汇海交通科技有限公司
 *
 * Copyright (c) 2025.
 * All rights reserved.
 *
 * 本软件属南京汇海交通科技有限公司所有，在未获得南京汇海交通科技有限公司正式授权情况下，任何企业和个人，不能获取、阅读、安装、传播本软件涉及的任何受知识产权保护的内容。
 */
package com.chframework.boot.web.event;

import com.chframework.boot.web.support.BaseUrlBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.reactive.WebFluxProperties;
import org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext;
import org.springframework.boot.web.reactive.context.ReactiveWebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.web.reactive.config.WebFluxConfigurer;

@Slf4j
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class)
public class ReactiveWebServerEventAdvice implements ApplicationListener<ReactiveWebServerInitializedEvent> {

    private static String baseUrl;

    /**
     * 在 ReactiveWebServerApplicationContext 已经刷新 并且 WebServer已经准备好 之后 发布的事件
     */
    @Override
    public void onApplicationEvent(@NonNull ReactiveWebServerInitializedEvent reactiveWebServerInitializedEvent) {
        log.debug("ReactiveWebServerInitializedEvent - Reactive(异步且非阻塞)响应式服务初始化完毕。");
        if (baseUrl != null) {
            return;
        }
        ReactiveWebServerApplicationContext applicationContext = reactiveWebServerInitializedEvent.getApplicationContext();
        WebFluxProperties webFluxProperties = applicationContext.getBean(WebFluxProperties.class);
        baseUrl = BaseUrlBuilder.createBaseUrlAboutSpringWeb(applicationContext, (serverProperties) -> webFluxProperties.getBasePath());
        log.info("Reactive(异步且非阻塞)响应式服务初始化完毕，访问地址是：{}", baseUrl);
    }

}
